// 域名对象
var hostList = {
    "houtai.siruijk.com": "http://admin.siruijk.com:8083/",
    "dev-houtai.siruijk.com": "http://193.112.138.106", //193.112.138.106 192.168.31.103
    "dev2-houtai.siruijk.com": "http://dev-admin.siruijk.com:8083/",
    "yd1.siruijk.com": "https://admin1.siruijk.com:8083/",
    "sit-yd.siruijk.com": "https://sit-admin.siruijk.com:8083/",
    "uat-yd.siruijk.com": "https://uat-admin.siruijk.com:8083/",
    "uat-yd1.siruijk.com": "https://uat-admin1.siruijk.com:8083/",
    "st-yd.siruijk.com": "http://st-admin.siruijk.com:8083/",
    "sit3-yd.siruijk.com": "https://sit3-admin.siruijk.com:8083/"
}
// 基础域名
var baseDomain = '';
var protocolStr = window.location.protocol
var hostStr = window.location.host;
var imgBaseDomain = protocolStr + '//' + hostStr;
angular.forEach(hostList, function(value, key) {
    if (key == hostStr) {
        baseDomain = value;
    }

})

require('./resource/css/bootstrap.css');
require('./resource/css/main.css');
require('./resource/css/common.css');
require('./lib/bubble/angular-growl.min.css');
require('./lib/dialog/ngDialog.min.css');
require('./lib/dialog/ngDialog-theme-default.min.css');


define([
    './lib/angular/ui-bootstrap-tpls.min',
    './lib/angular/angular-locale_zh-cn.min',
    './lib/bubble/angular-growl',
    './lib/dialog/ngDialog',
    './lib/angular/angular-cookie',
    './lib/angular/ng-file-upload-shim',
    './lib/angular/ng-file-upload',
    './lib/ngStorage/ngStorage',
    './lib/md5',
    './modules/user/namespace',
    './modules/device/namespace',
    './component/directives/namespace',
    './component/services/namespace',
    './component/filters/filters'
], function() {
    'use strict';
    return angular.module('app', ['ui.router', 'ngAnimate', 'ui.bootstrap', 'angular-growl', 'ngDialog', 'ipCookie', 'ngFileUpload', 'ngStorage', 'Encrypt', 'app.user', 'app.device', 'app.directives', 'app.services', 'app.filters'])
        .run(['$state', '$rootScope', '$timeout', '$sessionStorage', 'ngDialog', 'httpService', 'ENV', function($state, $rootScope, $timeout, $sessionStorage, ngDialog, httpService, ENV) {
            
            var getKeyFlag = 1;

            $rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
                if (!$sessionStorage.spvUser && toState.url !== '/login') {
                    // 确认框
                    ngDialog.open({
                        template: '\
                                <p class="dialogText">您未登陆,请先登陆</p>\
                                <div class="ngdialog-buttons">\
                                <button type="button" class="ngdialog-button ngdialog-button-primary dialogAloneBtn" ng-click="confirm();">确认</button>\
                            </div>\
                                ',
                        controller: ['$scope', '$state', function($scope, $state) {
                            $scope.confirm = function() {
                                //关闭弹窗
                                $scope.closeThisDialog();
                                $state.go('login');
                            }

                        }]
                    });

                } else {
                    // if (getKeyFlag) {
                    //
                    //     (function getSecretKey() {
                    //         httpService.linkHttp({
                    //             url: ENV.getPublicKeys,
                    //             exclude: false
                    //         }).then(function(res) {
                    //             $sessionStorage.spvPublic = JSON.stringify(res.data.data);
                    //             $rootScope.Public = res.data.data;
                    //         })
                    //         httpService.linkHttp({
                    //             url: ENV.getPrivateKeys,
                    //             exclude: false
                    //         }).then(function(res) {
                    //             $sessionStorage.spvPrivate = JSON.stringify(res.data.data);
                    //             $rootScope.Private = res.data.data;
                    //         })
                    //     }())
                    //
                    //  getKeyFlag = 0;
                    // }

                }
            })



        }])
        .config(['$stateProvider', '$urlRouterProvider', '$httpProvider', 'growlProvider', 'ngDialogProvider', function($stateProvider, $urlRouterProvider, $httpProvider, growlProvider, ngDialogProvider) {
            $urlRouterProvider.otherwise('/login');
            $stateProvider
                .state('login', {
                    url: '/login',
                    title: '登录',
                    templateUrl: 'login.html' + '?datestamp=' + (new Date()).getTime(),
                    controller: 'LoginCtrl'
                })
                .state('main', {
                    url: '/main',
                    templateUrl: 'main.html' + '?datestamp=' + (new Date()).getTime(),
                    controller: 'mainCtrl'
                })
                // 用户
                .state('main.user', {
                    url: '/user',
                    title: '用户',
                    templateUrl: 'userList.html' + '?datestamp=' + (new Date()).getTime(),
                    controller: 'userListCtrl'
                })
                .state('main.userDetail', {
                    url: '/userList/userDetail/:userId',
                    title: '用户详情',
                    templateUrl: 'userDetail.html' + '?datestamp=' + (new Date()).getTime(),
                    controller: 'userDetailCtrl'
                })
                .state('main.addUser', {
                    url: '/addUser',
                    title: '新增用户',
                    templateUrl: 'addUser.html' + '?datestamp=' + (new Date()).getTime(),
                    controller: 'addUserCtrl'
                })
                // 设备
                .state('main.device', {
                    url: '/device',
                    title: '设备列表',
                    templateUrl: 'deviceList.html' + '?datestamp=' + (new Date()).getTime(),
                    controller: 'deviceListCtrl'
                })
                .state('main.deviceDetail', {
                    url: '/device/details/:id',
                    title: '设备详情',
                    templateUrl: 'deviceDetail.html' + '?datestamp=' + (new Date()).getTime(),
                    controller: 'deviceDetailCtrl'
                })
                .state('main.addDevice', {
                    url: '/addDevice',
                    title: '新增设备',
                    templateUrl: 'addDevice.html' + '?datestamp=' + (new Date()).getTime(),
                    controller: 'addDeviceCtrl'
                })
                .state('main.workDevice', {
                    url: '/device/workDevice',
                    title: '工作设备列表',
                    templateUrl: 'workDevice.html' + '?datestamp=' + (new Date()).getTime(),
                    controller: 'workDeviceCtrl'
                });
                // 设置后请求带cookies
            $httpProvider.defaults.withCredentials = true;
            $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
            $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
            $httpProvider.defaults.transformRequest = [function(data) {
                /**
                 * The workhorse; converts an object to x-www-form-urlencoded serialization.
                 * @param {Object} obj
                 * @return {String}
                 */
                var param = function(obj) {
                    var query = '';
                    var name, value, fullSubName, subName, subValue, innerObj, i;
                    for (name in obj) {
                        value = obj[name];
                        if (value instanceof Array) {
                            for (i = 0; i < value.length; ++i) {
                                subValue = value[i];
                                fullSubName = name + '[' + i + ']';
                                innerObj = {};
                                innerObj[fullSubName] = subValue;
                                query += param(innerObj) + '&';
                            }
                        } else if (value instanceof Object) {
                            for (subName in value) {
                                subValue = value[subName];
                                if (subValue != null) {
                                    // fullSubName = name + '[' + subName + ']';
                                    //user.userName = hmm & user.userPassword = 111
                                    fullSubName = name + '.' + subName;
                                    // fullSubName =  subName;
                                    innerObj = {};
                                    innerObj[fullSubName] = subValue;
                                    query += param(innerObj) + '&';
                                }
                            }
                        } else if (value !== undefined) //&& value !== null
                        {
                            query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
                        }
                    }
                    return query.length ? query.substr(0, query.length - 1) : query;
                };
                return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
            }]
            $httpProvider.defaults.useXDomain = true;
            // 配置growl消失时间
            growlProvider.globalTimeToLive(1500);
            // 配置NGdialog
            ngDialogProvider.setDefaults({
                className: 'ngdialog-theme-default',
                plain: true,
                showClose: false, //不显示关闭按钮
                closeByDocument: false, //禁止点击空白处退出modal
                closeByEscape: false //禁止按esc退出modal
            });
        }])
        .controller('appCtrl', ['$scope', '$state', '$timeout', '$location', '$sessionStorage', 'ngDialog', 'growl', 'httpService', 'ENV', function($scope, $state, $timeout, $location, $sessionStorage, ngDialog, growl, httpService, ENV) {

            $scope.url = 'http://' + $location.host();
            // 登出
            $scope.logout = function() {
                // 确认框
                ngDialog.open({
                    template: '\
                            <p class="dialogText">您是否确认退出登录? </p>\
                            <div class="ngdialog-buttons">\
                                <button type="button" class="ngdialog-button ngdialog-button-primary dialogBtn" ng-click="confirm();">确认</button>\
                                <button type="button" class="ngdialog-button ngdialog-button-secondary dialogBtn" ng-click="closeThisDialog()">取消</button>\
                            </div>',
                    controller: ['$scope', function($scope) {
                        $scope.confirm = function() {
                            $scope.user = JSON.parse($sessionStorage.spvUser);
                            httpService.linkHttp({
                                url: ENV.logout
                            },{token:$scope.user.token}).then(function(res) {
                                if (res.data.code == "000000") {
                                    delete $sessionStorage.spvUser;
                                    delete $sessionStorage.spvMenuList;
                                    delete $sessionStorage.spvPublic;
                                    delete $sessionStorage.spvPrivate;
                                    $state.go('login');
                                } else {
                                    growl.addErrorMessage("登出失败");
                                }
                                //关闭弹窗
                                $scope.closeThisDialog();
                            })
                        }
                    }]
                });
            }

            //菜单隐藏显示切换 
            $scope.fold = false;
            $scope.toggleFold = function() {
                    $scope.fold = !$scope.fold;
                }
                //弹窗
            $scope.alert = function(text) {
                $scope.isAlert = true;
                $scope.alertText = text;
                $timeout(function() {
                    $scope.isAlert = false;
                }, 1000)
            }


        }])
        .controller('mainCtrl', ['$rootScope', '$scope', '$state', '$timeout', '$sessionStorage', 'httpService', 'ENV', 'growl', function($rootScope, $scope, $state, $timeout, $sessionStorage, httpService, ENV, growl) {

            $rootScope.imgBaseDomain = imgBaseDomain;
            // 保存用户信息
            $sessionStorage.spvUser ? $scope.userInfo = JSON.parse($sessionStorage.spvUser) : $scope.userInfo = null;
            console.log($scope.userInfo);
            if ($scope.userInfo) {
                $scope.userInfo.userType = $scope.userInfo.userInfo.userType;
                $scope.token = $scope.userInfo.token;
            }

            // 表单错误字段弹出
            $rootScope.chechErrorForm = function(errObj) {
                var flag = 1;
                angular.forEach(errObj, function(v, k) {
                    if (flag) {
                        v.every(function(v2, k2) {
                            var text = v2.$$attr.desc || '';
                            growl.addInfoMessage('请正确填写' + text + '信息');
                            v2.$$element[0].focus();
                            flag = 0;
                            return false;
                        })
                    }
                });
                flag = 1;
            };

            // 获取菜单树
            $scope.menuTreesDisplay = false;

            // 本地有菜单树取本地
            if ($sessionStorage.spvMenuList) {
                $scope.menuList = window.JSON.parse($sessionStorage.spvMenuList);
                $scope.menuTreesDisplay = true;
            }

            // $sessionStorage.spvMenuList = window.JSON.stringify($scope.menuList);
            // $scope.menuTreesDisplay = true;
            // 首次进入获取菜单树
            console.log(1);
            if ($scope.userInfo && !$scope.menuList) {
                httpService.linkHttp({
                    url: ENV.menu
                }).then(function(res) {
                    // 判断请求成功
                    var data = res.data;
                    if (data.code == "000000") {
                        var data = data.data;
                        if (data.menuList) {
                            $scope.menuList = data.menuList;
                            $sessionStorage.spvMenuList = window.JSON.stringify($scope.menuList);
                            $scope.menuTreesDisplay = true;
                        }
                    }
                });
            }


            //时间控件配置
            $scope.dateOptions = {
                showWeeks: false,
                startingDay: 1
            };
            // 时间控件标识
            $scope.datePopup = {
                openedStart: false,
                openedEnd: false
            };
            // 时间控件开关
            $scope.openDate = function(flag) {
                flag == 1 ? $scope.datePopup.openedStart = true : $scope.datePopup.openedEnd = true;
            };


        }])
        .controller('LoginCtrl', ['$scope', '$state', '$localStorage', '$sessionStorage', 'Md5', 'httpService', 'ENV', 'Crypt', function($scope, $state, $localStorage, $sessionStorage, Md5, httpService, ENV, Crypt) {
            // 回车键登陆
            $scope.myKeyup = function (e) {
                var keycode = window.event ? e.keyCode : e.which;
                if (keycode == 13) {
                    $scope.login();
                }
            };

            // 表单信息
            $scope.form = {
                mobile: '',
                password: ''
            }

            //记住密码标识
            $scope.isRemember = false;
            $scope.toggleRemember = function () {
                $scope.isRemember = !$scope.isRemember;
            };

            //查询表单记录
            if ($localStorage.spvRecord) {
                var record = JSON.parse(unescape($localStorage.spvRecord));
                $scope.isRemember = true;
                $scope.form = {
                    mobile: record.mobile,
                    password: record.password
                }
            }

            //登录请求
            $scope.login = function () {
                // $state.go('main.user');
                var data = {
                    account: $scope.form.mobile,
                    // password: Crypt.sha512($scope.form.password+'&'+$scope.form.mobile)
                    password: Md5.hex_md5($scope.form.password)
                };
                // 登陆请求
                console.log(2);
                httpService.linkHttp({
                    url: ENV.login
                }, data).then(function (data) {
                    $scope.data = data.data.data;
                    if (data.data.code != '000000' || !data.data.msg) {
                        $scope.alert(data.data.msg)
                    } else {
                        if ($scope.isRemember) { //记住密码
                            $localStorage.spvRecord = escape(JSON.stringify($scope.form));
                        } else { //单次登录
                            if ($localStorage.spvRecord) {
                                delete $localStorage.spvRecord;
                            }
                        }
                        $sessionStorage.spvUser = JSON.stringify($scope.data);
                        $state.go('main.user');
                    }
                })
            }
        }])
        .constant("ENV", {
            "login": baseDomain + "/web/api/open/back/omsLogin", //登录
            "logout": baseDomain + "/web/api/inner/user/loginOut", //退出
            "menu": baseDomain + "/web/api/inner/user/getOmsMenu", //菜单
            // "getPublicKeys": baseDomain + "platform/getPublicKeys", //公钥
            // "getPrivateKeys": baseDomain + "platform/getPrivateKeys", //私钥
            // "listByKeyAndType": baseDomain + "spvweb/inner/config/listByKeyAndType", //字典项列表获取
            // 用户管理
            "userList": baseDomain + "/web/api/inner/user/userList", //用户列表
            "userDetail": baseDomain + "/web/api/inner/user/userDetail", //用户详情
            "userEdit": baseDomain + "/web/api/inner/user/userEdit", //用户编辑
            "userAdd": baseDomain + "/web/api/inner/user/userAdd", //用户新增
            "userDelete": baseDomain + "/web/api/inner/user/userDelete", //用户删除

            // 机器管理
            "deviceList": baseDomain + "/web/api/inner/device/deviceList", //设备列表
            "deviceDetail": baseDomain + "/web/api/inner/device/deviceDetail", //设备详情
            "deviceDelete": baseDomain + "/web/api/inner/device/deviceDelete", //设备删除
            "deviceOprate": baseDomain + "/web/api/inner/device/deviceOprate", //设备锁定
            "deviceAdd": baseDomain + "/web/api/inner/device/deviceAdd", //设备新增
            "deviceEdit": baseDomain + "/web/api/inner/device/deviceEdit", //设备修改
            "deviceWorkList": baseDomain + "/web/api/inner/device/deviceWorkList", //设备工作信息列表


        })

});